import React, { useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Popup, Tabs } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { getUserChannelAsync } from '@/store/actions/home'
import Icon from '@/components/Icon'
import Channels from './Channels'
import ArticleList from './ArticleList'
export default function Home() {
  const dispatch = useDispatch()
  useEffect(() => {
    // 获取用户频道数据并存redux
    dispatch(getUserChannelAsync())
  }, [dispatch])
  const channels = useSelector((state) => state.home.userChannels)
  // 默认激活的频道索引
  const [activeIndex, setActiveIndex] = useState('0')
  // 默认激活的频道id
  const [activeId, setActiveId] = useState(0)
  // 切换tab更改激活频道的索引
  const onChangeIndex = (key) => {
    // key就是当前点击的tab的索引
    setActiveIndex(() => key)
    // 设置激活的id
    setActiveId(channels[key].id)
  }
  // 频道管理弹层
  const [visible, setVisible] = useState(false)
  // 关闭弹层的处理事件
  const closeHandler = () => {
    setVisible(false)
  }

  // 点击频道管理中我的频道需要做的事情
  const onChannelClick = (index) => {
    // 避免用户在编辑状态点击频道时发生跳转
    // 设置激活的tab
    setActiveIndex(index + '')
    // 关闭弹层
    setVisible(false)
  }

  return (
    <div className={styles.root}>
      <Tabs
        // 当前激活的tab,必须是string类型
        activeKey={activeIndex}
        onChange={onChangeIndex}
        activeLineMode="auto"
        style={{
          color: '#9ea1ae',
          '--active-line-color': '#fc6627',
          '--active-title-color': '#333',
          '--content-padding': 0,
        }}
      >
        {channels.map((item, index) => (
          <Tabs.Tab title={item.name} key={index}>
            {/* 每个tab对应的内容在此显示 */}
            <ArticleList
              channel_id={item.id}
              active_id={activeId}
            ></ArticleList>
          </Tabs.Tab>
        ))}
      </Tabs>

      {/* 频道 Tab 栏右侧的两个图标按钮：搜索、频道管理 */}
      <div className="tabs-opration">
        <Icon type="iconbtn_search" />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      {/* 频道管理的抽屉 */}
      <Popup
        visible={visible}
        onMaskClick={closeHandler}
        position="left"
        onClose={closeHandler}
        bodyStyle={{ width: '100vw' }}
      >
        <Channels
          onClose={closeHandler}
          tabActiveIndex={activeIndex}
          onChannelClick={onChannelClick}
        ></Channels>
      </Popup>
    </div>
  )
}
